/**
 * Project : CTI-dev
 * Package : com.voipackjapan.cti.utils
 * File    : DESEncryptUtil.java
 */
package com.jcnet.bizaia.tools;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.SecretKeySpec;

/**
 * <code>DESEncryptUtil</code>
 * description.<p>
 * 
 * <blockquote><pre>
 * use for ...
 * </pre></blockquote>
 * 
 * @author Zhou Yin (<a href="mailto:vambad@gmail.com">Contact Me</a>)
 * @version 1.0, 2009-11-25
 * @since 1.0
 */
public class DESUtil {

	public static final String			SECURITY_DES_ENC		= "DES";
	public static final String			SECURITY_SEED			= "vambad86";
	
	public static String encrypt(String str) throws InvalidKeyException, NoSuchAlgorithmException, NoSuchPaddingException, IllegalBlockSizeException, BadPaddingException, UnsupportedEncodingException {
		byte [] key = SECURITY_SEED.getBytes();
		
		DESKeySpec desKeySpec = new DESKeySpec(key);
		SecretKeySpec keySpec = new SecretKeySpec(desKeySpec.getKey(), SECURITY_DES_ENC);
		
		Cipher cipher = Cipher.getInstance(SECURITY_DES_ENC);
		cipher.init(Cipher.ENCRYPT_MODE, keySpec);
		
		byte[] enc = cipher.doFinal(str.getBytes("UTF8"));
		
		return Hex.encodeHexString(enc);
	}
	
	public static String decrypt(String str) throws Exception {
		byte[] key = SECURITY_SEED.getBytes();
		
		DESKeySpec deskey = new DESKeySpec(key);
		SecretKeySpec keySpec = new SecretKeySpec(deskey.getKey(), SECURITY_DES_ENC);
		
		Cipher cipher = Cipher.getInstance(SECURITY_DES_ENC);
		cipher.init(Cipher.DECRYPT_MODE, keySpec);
		
		byte[] dec = cipher.doFinal((byte [])new Hex().decode(str));
		
		return new String(dec, "UTF8");
	}

	public static void main(String args[]) throws Exception {
		System.out.println(DESUtil.encrypt("3G7nVsG") + "#");
		System.out.println(DESUtil.decrypt("53452d26ff447e7e") + "#");
	//	System.out.println(DESUtil.decrypt("Cj3T8yIQ7jo=") + "#");
	}
	
}
